package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.CollectionBehaviorDto;
import com.heima.behavior.pojos.ApCollectionBehavior;
import com.heima.behavior.service.ApCollectionBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


@Service
public class ApCollectionBehaviorServiceImpl implements ApCollectionBehaviorService {


    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto dto) {
        if(dto==null||dto.getEntryId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否是游客
        ApUser apUser = AppThreadLocal.getApUser();
        Integer id = apUser.getId();
        if(id==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String articleCollection="USER_COLLECTION_"+dto.getEntryId();
        Boolean hasKey = redisTemplate.opsForHash().hasKey(articleCollection,id+"");

        if(hasKey&&dto.getType()==0){
            return ResponseResult.okResult("已经加入收藏的队列中");
        }
        //取消点赞   删除redis和mongodb
        if(hasKey&&dto.getType()==1){
            redisTemplate.opsForHash().delete(articleCollection, apUser.getId()+"");
            Query query = Query.query(Criteria.where("userId").is(apUser.getId().longValue()).and("entryId").is(dto.getEntryId()));
            mongoTemplate.remove(query, ApCollectionBehavior.class);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        if(!hasKey&&dto.getType()==0){
            //在redis和mongodb中添加数据
            redisTemplate.opsForHash().put(articleCollection, id+"", "1");
            ApCollectionBehavior apCollectionBehavior = new ApCollectionBehavior();
            apCollectionBehavior.setType(Short.parseShort(0+""));
            apCollectionBehavior.setUserId(apUser.getId().longValue());
            apCollectionBehavior.setEntryId(dto.getEntryId());
            mongoTemplate.save(apCollectionBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.okResult(null);
    }
}
